package io.gitee.minelx.commontools;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Objects;

public class Files {
	public static String toString(String path) {
		return toString(path, Charset.defaultCharset());
	}

	public static String toString(String path, Charset charset) {
		return toString(Objects.requireNonNull(Files.class.getResourceAsStream(path)), charset);
	}

	public static String toString(InputStream input) {
		return toString(input, Charset.defaultCharset());
	}

	public static String toString(InputStream input, Charset charset) {
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		try {
			byte[] buffer = new byte[1024];
			int len;
			while ((len = input.read(buffer)) != -1) {
				result.write(buffer, 0, len);
			}
			return result.toString(charset.name());
		} catch (IOException e) {
			throw new RuntimeException("can't read the stream.");
		}
	}
}